package tazadum.engine.ui;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class ParameterManager {
	private boolean debug;
	private JFrame frame;

	private final List<Parameter> parameters = new LinkedList<Parameter>();

	public ParameterManager() {
	}

	public synchronized void setDebug(final boolean debug) {
		this.debug = debug;
	}

	public synchronized void register(final String name, final String field, final Object obj) {
		if (!debug) {
			return;
		}
		parameters.add(new Parameter(name, field, obj));
		updateUI();
	}

	public synchronized void show() {
		if (frame == null) {
			frame = new JFrame("Parameters");
			frame.getContentPane().setLayout(new VerticalFlowLayout());
			updateUI();
			frame.setVisible(true);
			frame.addWindowListener(new WindowAdapter() {
				@Override
				public void windowClosing(final WindowEvent e) {
					dumpParameters();
				}
			});
		}
	}

	protected void dumpParameters() {
		System.out.println("---- Parameters -----");
		for (final Parameter p : parameters) {
			System.out.println(String.format("%s = %.3ff;", p.field, p.value));
		}
	}

	private synchronized void updateUI() {
		if (frame == null) {
			return;
		}

		final Container pane = frame.getContentPane();
		pane.removeAll();

		for (final Parameter parameter : parameters) {
			final JTextField textField = new JTextField(String.valueOf(parameter.value));
			textField.getDocument().addDocumentListener(new DocumentListener() {
				@Override
				public void removeUpdate(final DocumentEvent arg0) {
					pushValue(parameter, textField.getText());
				}

				@Override
				public void insertUpdate(final DocumentEvent arg0) {
					pushValue(parameter, textField.getText());
				}

				@Override
				public void changedUpdate(final DocumentEvent arg0) {
					pushValue(parameter, textField.getText());
				}
			});

			final JPanel panel = new JPanel(new FlowLayout());
			panel.add(new JLabel(parameter.clazz + ": " + parameter.name));
			panel.add(textField);
			pane.add(panel);
		}
		frame.pack();
	}

	protected void pushValue(final Parameter parameter, final String text) {
		try {
			final float value = Float.parseFloat(text);
			parameter.push(value);
		} catch (final NumberFormatException e) {
		}
	}
}
